// uploadStore.js
import { defineStore } from 'pinia';
import { v4 as uuidv4 } from 'uuid';
import { useUserStore } from './userStore';


const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB per chunk, adjust as needed
// @ts-ignore
export const useUploadStore = defineStore('upload', {
  state: () => ({
    uploads: [], // 存储当前用户的上传文件信息，包括文件、分块信息、进度和唯一标识
  }),
  actions: {
    // 添加新文件到上传列表，并初始化分块信息
    addFile(file: File):string {
      const userStore = useUserStore();
      const userId = userStore.user?.id;

      if (!userId) {
        throw new Error('No user logged in');
      }

      // 检查文件是否已经存在于上传列表中
      const existingUpload = this.uploads.find(upload => upload.fileName === file.name && upload.fileSize === file.size);
      if (existingUpload) {
        ElMessage.error('文件已存在于上传列表中，请勿重复上传');
        return; // 如果文件已存在，则不继续添加并返回
      }

      const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
      const upload = {
        fileName: file.name,
        fileSize: file.size,
        fileType: file.type,
        chunks: Array(totalChunks).fill({ uploaded: false, progress: 0 }),
        progress: 0,
        fileId: uuidv4(),// 生成一个唯一的文件ID
        userId: userStore.user?.id,
      };

      this.uploads.push(upload);
      return upload.fileId;
    },
  
    // 标记特定分块为已上传，并更新整个文件的上传进度
    markChunkAsUploaded(uploadId, chunkIndex) {
      const upload = this.uploads.find(u => u.fileId === uploadId);

      if (upload && upload.chunks[chunkIndex]) {
        upload.chunks[chunkIndex].uploaded = true;
        // 在这里调用 updateOverallProgress 来更新文件进度
        this.updateOverallProgress(upload);
      } else {
        throw new Error('Upload or chunk not found');
      }
    },

    // 更新整个文件的上传进度（保持不变）
    updateOverallProgress(upload) {
      const totalChunks = upload.chunks.length;
      const uploadedChunks = upload.chunks.filter(chunk => chunk.uploaded).length;
      upload.progress = Math.round((uploadedChunks / totalChunks) * 100);
    },    // 清除已完成的上传或根据其他条件清除上传列表
    clearUploads() {
      this.uploads = [];
    },
    removeUpload(FileID) {
      this.uploads = this.uploads.filter(upload => upload.fileId !== FileID);
    },
  
  },
  getters: {
    // 获取当前用户的上传文件列表
    currentUploads(state) {
      const userStore = useUserStore();
      const userId = userStore.user?.id;
      return userId ? state.uploads.filter(upload => upload.userId === userId) : [];
    },
  },
  persist: {
    key: 'uploadStore',
    storage: localStorage,
    paths: ['uploads'],
  },
});